package com.auto.survey.activity.monitoring.project

import android.graphics.Color
import android.text.TextUtils
import android.view.View
import android.widget.EditText
import androidx.lifecycle.lifecycleScope
import com.auto.survey.R
import com.auto.survey.activity.monitoring.dao.MonitoringRepository
import com.auto.survey.activity.monitoring.entity.MontoringProject
import com.auto.survey.base.BaseActivity
import com.auto.survey.util.Helper
import com.auto.survey.widget.CentreToast
import com.auto.survey.widget.CommonTitle.Companion.TEXT_POSITON_RIGHT
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.launch
import kotlinx.coroutines.withContext

/**
 * 新建项目
 */
class CreateProjectActivity:BaseActivity() {

    private val database = MonitoringRepository()

    override fun initView() {

        val edit_projectName = findViewById<EditText>(R.id.edit_create_montoring_projectname)

        mTopBar?.visibility = View.VISIBLE
        mTopBar?.setBackgroundResource(R.color.action_bar)

        mComment_title?.visibility = View.VISIBLE
        mComment_title?.setBackgroundResource(R.color.action_bar)
        mComment_title?.setTitle("创建项目")

        mComment_title?.setRightTitle("保存")
        mComment_title?.setTitleColor(Color.WHITE, TEXT_POSITON_RIGHT)
        mComment_title?.setOnRightTextClickListener(Helper.debounce{

            val projectName = edit_projectName.text.toString()
            val creatTime = System.currentTimeMillis()

            if (TextUtils.isEmpty(projectName)){
                CentreToast.instance.show("项目名称不可为空", false)
                return@debounce
            }

            val project = MontoringProject(montoringProjectName = projectName, createTime = Helper.formatTimestamp(creatTime), updateTime ="")
            lifecycleScope.launch {
                val succ = database.createProject(project)
                withContext(Dispatchers.Main) {
                    if (succ.toInt() != -1) {
                        CentreToast.instance.show("创建成功", true)
                    } else {
                        CentreToast.instance.show("创建失败", true)
                    }
                    finish()
                }

            }
        })
    }

    override fun getLayoutId(): Int {

        return R.layout.activity_create_montoring_project
    }
}